<!--  -->
<script setup>
import SimpleInput from '@/components/input/SimpleInput.vue'
import SubmitBtn from '@/components/button/SubmitBtn.vue'
import RankSwitcher from '@/components/RankSwitcher.vue'
import { getTagListAPI } from '@/apis/tag'
import TagCard from './components/TagCard.vue'
import { useBreadsStore } from '@/stores'
import { RouterLink, useRoute, useRouter } from 'vue-router'
import { onMounted, ref } from 'vue'
import { us } from '@/utils/userState'

const { setBreadCrumbs } = useBreadsStore()
setBreadCrumbs([{ title: '标签列表' }])

const route = useRoute()
const router = useRouter()
const initOrder = route.query.order || 'newest'
const data = ref([])
const tagFilter = ref('')
let initData = null

onMounted(() => retrieveData(route.query.order || 'newest'))

const orderType = [
  { title: '最新', order: 'newest' },
  { title: '最热', order: 'hot' },
  { title: '名称', order: 'alphabetical' },
]

function onSwitchOrder(type) {
  router.push({ query: { order: type } })
  retrieveData(type)
}

function retrieveData(order) {

  getTagListAPI({ pageNo: 0, pageSize: 10, order }).then(res => {
    initData = data.value = res.data.records
  }).catch(() => null)
}

function filterTag() {
  if (!tagFilter.value) {
    data.value = initData
    return
  }
  data.value = data.value.filter(v => v.displayName.includes(tagFilter.value))

}
</script>

<template>
  <div class="view-container">
    <div class="header flex-between">
      <div>标签</div>
      <RankSwitcher :init-type="initOrder" v-on:on-switch-order="onSwitchOrder" :order-type="orderType"></RankSwitcher>
    </div>
    <div class="flex-between">
      <SimpleInput @input="filterTag" v-model="tagFilter" placeholder="通过标签名过滤" />
      <RouterLink v-if="us.isAdmin || us.isStaff" to="/tags/create">
        <SubmitBtn>添加新标签</SubmitBtn>
      </RouterLink>
    </div>
    <div class="body">
      <TagCard v-for="v in data" :key="v.id" :tag="v.displayName" :desc="v.content" :cnt="v.questionCount" />
    </div>
  </div>
</template>

<style scoped lang="scss">
.view-container {
  min-height: 100%;
  margin-right: 4em;
}

.header {
  padding-bottom: 1em;
  margin-bottom: 1em;
  border-bottom: 1px dashed var(--border-secondary);
}

.body {
  display: flex;
  flex-wrap: wrap;
  gap: 1em;
  margin: 1em 0;
}
</style>
